#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
day 29 homework
"""
# 1.文件的上传、下载
# 2.结合用户认证
# 要求：
# 1.tcp协议粘包的问题，使用struct模块解决粘包问题
# 2.传递的所有的信息都尽量是json格式
# 3.再server端用上反射

import os
import json
import struct
import hashlib
from socket import socket


class HomePage(object):
    def get_md5(self, data):
        """
        md5加密
        :param data: 明文
        :return: 密文
        """
        obj = hashlib.md5('f8c2s8z2c2.j5,5.[]4jf92d'.encode('utf-8'))
        obj.update(data.encode('utf-8'))
        return obj.hexdigest()

    def get_size(self, data):
        data_size = struct.pack('i', data)
        return data_size

    def login(self):
        while True:
            sk.send('1'.encode('utf-8'))
            info = dict()
            user = input('请输入用户名：')
            pwd = input('请输入密码：')
            info['user'] = user
            info['pwd'] = self.get_md5(pwd)
            sk.send(json.dumps(info).encode('utf-8'))
            msg = sk.recv(1024).decode('utf-8')
            if msg.upper() == 'T':
                global LOGIN_FLAG
                LOGIN_FLAG = True
                print('登录成功！')
                print('#################')
                break
            elif msg.upper() == 'F':
                print('用户名或密码错误！')
                continue

    def file_up(self):
        if LOGIN_FLAG:
            sk.send('2'.encode('utf-8'))
            path = input('请输入你要上传的文件路径：')
            file_size = os.path.getsize(path)
            size = self.get_size(file_size)
            file_name = os.path.basename(path)
            file_name_size = self.get_size(len(file_name))
            sk.send(file_name_size)
            sk.send(file_name.encode('utf-8'))
            sk.send(size)
            with open(path, 'rb') as f:
                count = 0
                while file_size > count:
                    res = f.read(1024)
                    sk.send(res)
                    count += 1024
            msg = sk.recv(1024).decode('utf-8')
            print(msg)
        else:
            print('请先登录')


    def file_down(self):
        if LOGIN_FLAG:
            sk.send('3'.encode('utf-8'))
            file_list = sk.recv(1024).decode('utf-8')
            count = 0
            for i in file_list:
                print('%s.%s' % (count, i))
                count += 1
            file = file_list[int(num) - 1]
            sk.send(file.encode('utf-8'))
            file_name_size = sk.recv(4)
            file_name_size = struct.unpack('i', file_name_size)[0]
            file_name = sk.recv(file_name_size).decode('utf-8')
            size = sk.recv(4)
            size = struct.unpack('i', size)[0]
            with open(os.path.join('G:\code\project1', file_name), 'wb') as f:
                count = 0
                while size > count:
                    msg = sk.recv(1024)
                    f.write(msg)
                    count += 1024
            print('下载成功')
        else:
            print('请先登录')

LOGIN_FLAG = False
sk = socket()
sk.connect(('127.0.0.1', 9001))
while True:
    print(
        '1.登录\n'
        '2.上传\n'
        '3.下载'
    )
    home_dict = {'1': 'login', '2': 'file_up', '3': 'file_down'}
    num = input('请输入序号：')
    obj = HomePage()
    getattr(obj, home_dict[num])()
